/*
 * Powered By [rapid-framework]
 * Csdn Code: generate simple CRUD code in single table.
 * Since 2015 - 2017
 */

BUI.use('common/page');
BUI.use(['common/search', 'bui/overlay', 'bui/grid', 'bui/data', 'bui/form','bui/select','bui/mask'],
    function (Search, Overlay, Grid, Data, Form,Select,Mask) {
      // 查询表单
        var form = new Form.Form({
            srcNode: '#searchForm'
        }).render();
        var statusEnum = {
            '1': '显示贷款超市',
            '0': '隐藏贷款超市'
        };
        var items=[];
        var textItems=[];
        var onlineStatusEnum=[];
        var onlineStatusJson={};
        $.ajaxSettings.async = false;
        $.getJSON('listAllChannels',function (channels) {
            for(var i=0;i<channels.length;i++){
                items[i]=channels[i].value;
                textItems[i]=channels[i].text;
            }
        });
        $.getJSON('listAllOnlineStatus',function (onlineStatusData) {
            onlineStatusEnum=onlineStatusData;
            for(var i=0;i<onlineStatusData.length;i++){
                toJson(onlineStatusJson,onlineStatusData[i].value+'',onlineStatusData[i].text);
            }
        });
        $.ajaxSettings.async = true;
        var selectData = {'enumRenderer':'true','items':onlineStatusEnum};
        $("#onlineStatusSelect").attr('data-select',JSON.stringify(selectData));
        var suggest1 = new Select.Suggest({
            render:'#channelSelect',
            value: '#channel',
            data:items
        });
        suggest1.render();
        suggest1.on('change', function(ev) {
            $("#channel").val(ev.value);
        });
        var suggest2 = new Select.Suggest({
            render:'#channelDescSelect',
            value: '#channelDesc',
            data:textItems
        });
        suggest2.render();
        suggest2.on('change', function(ev) {
            $("#channelDesc").val(ev.value);
        });
        function toJson(array, prop, val) {
            // 如果 val 被忽略
            if (typeof val === "undefined") {
                // 删除属性
                delete array[prop];
            } else {
                // 添加 或 修改
                if (val.length > 0) {
                    array[prop] = val;
                }
            }
        }
      // 定义表头
        columns = [
            {
                title: 'id',
                dataIndex: 'channelId',
                visible: false
            },{
                title: 'channelBusinessId',
                dataIndex: 'channelBusinessId',
                visible: false
            }, {
                title: '渠道',
                dataIndex: 'channel',
                elCls: 'center',
                width: 120
            }, {
                title: '渠道描述',
                dataIndex: 'channelDesc',
                elCls: 'center',
                width: 150
            }, {
                title: '渠道状态',
                render: '.test',
                dataIndex: 'status',
                elCls: 'center',
                width: 80,
                renderer: BUI.Grid.Format
                    .enumRenderer(statusEnum)
            }, {
                title: '开始对接时间',
                dataIndex: 'businessStartDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '合同开始时间',
                dataIndex: 'contractStartDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '合同完成时间',
                dataIndex: 'contractEndDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '准备上线时间',
                dataIndex: 'prepareOnlineDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '上线开始时间',
                dataIndex: 'onlineStartDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '下线时间',
                dataIndex: 'onlineEndDate',
                elCls: 'center',
                width: 120,
                renderer : BUI.Grid.Format.datetimeRenderer
            }, {
                title: '当前上线状态',
                render: '.test',
                dataIndex: 'onlineStatus',
                elCls: 'center',
                width: 80,
                renderer: BUI.Grid.Format
                    .enumRenderer(onlineStatusJson)
            }, {
                title: '备注',
                dataIndex: 'remarks',
                elCls: 'center',
                width: 200
            },{title:'操作',
                dataIndex:'',
                elCls: 'center',
                width:80,
                renderer : function(value,obj){
                    var   editStr = '<span class="grid-command btn-edit" title="编辑信息">编辑</span>';
                    return editStr;
                }
            }];
      // 编辑
        var editing = new Grid.Plugins.DialogEditing({
                contentId : 'content',
                triggerCls : 'btn-edit',
                editor : {
                    title : '渠道添加或修改',
                    width : 400
                }
            }),
          // 获取数据
          store = new BUI.Data.Store({
            url: 'listRegisterChannel',
            pageSize: 20,
            autoLoad: true,
            remoteSort: true
          });
      // 获取表格对象
        gridCfg = Search.createGridCfg(columns, {
          plugins: [editing, Grid.Plugins.CheckSelection],
          tbar: { // 添加
            items: [{
              btnCls: 'button button-small',
              text: '<i class="icon-plus"></i>添加',
              listeners: {
                'click': addFunction
              }
            }, {
              btnCls: 'button button-small',
              text: '<i class="icon-refresh"></i>刷新',
              listeners: {
                'click': refreshFunction
              }
            }]
          }
        });
      // 编辑提交
      editing.on('accept', function (ev) {
          Mask.maskElement('body');
        var record = editing.get('record');
        var channel=record.channel;
        if (record.hasOwnProperty("b")) {
          delete record["b"];
        }
        if (record.hasOwnProperty("")) {
          delete record[""];
        }
        var saveUrl = record["channelId"] == "" ? 'saveRegisterChannel'
              : 'updateRegisterChannel';
        if(saveUrl=='saveRegisterChannel'){
            var flag=false;
            $.ajaxSettings.async = false;
            $.getJSON('listAllChannels',function (channels) {
                for(var i=0;i<channels.length;i++){
                    if(channel==channels[i].value){
                        flag=true;
                        break;
                    }
                }
            });
            if(flag){
                BUI.Message.Alert('渠道重复！');
                return;
            }
            $.ajaxSettings.async = true;
        }
        jQuery.ajax({
          type: 'POST',
          url: saveUrl,
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(record),
          complete: function (data) {
            if (data.responseText == "success") { // 删除成功
              search.load();
            } else if(data.responseText=="exit"){
                BUI.Message.Alert("渠道已存在");
            }else { // 删除失败
                BUI.Message.Alert('保存失败！');
            }
          }
        });
      });

      // 添加记录
      function addFunction() {
          var newData = {channel :'请填写渠道英文名',onlineStatus:'1'};
          editing.add(newData);
      }
      // 刷新
      function refreshFunction() {
        search.load();
      }

      // 查询
      search = new Search({
        store: store,
        autoSearch: true,
        gridCfg: gridCfg
      });
      grid = search.get('grid');
    });